#include "dbbook.h"
#include <QMessageBox>
dbBook::dbBook(QObject *parent) :
    QObject(parent)
{
    dbstatus = DISCONNECTED;
}

dbBook::~dbBook()
{
    closedb();
}

int dbBook::connectdb()
{
    bool hasbookDB = false;
    QFileInfo fi("book.db");                     // 目录存在
    if(fi.isFile())
        hasbookDB = true;
    QString qstr("create table book (isbn char(20) primary key,"
                 "title varchar(255),available varchar(16),borrower varchar(255),"
                 "author varchar(255),tag varchar(255),pub varchar(255),price double)"
            );
    db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("book.db");
    if (!db.open())
    {
        QMessageBox::critical(NULL, "sqlDB","connect error");
        return -1;
    }
    dbstatus = CONNECTED;

    if(!hasbookDB)
    {
        QSqlQuery query(db);
        query.exec(qstr);
    }
    return 1;
}

void dbBook::closedb()
{
    if(db.isOpen())
        db.close();
}

DBstatus dbBook::getDBstatus()
{
    return dbstatus;
}

bool dbBook::IsbnIsNormative(QString &isbn)
{
    int len = isbn.length();
    if(len!=10 && len!=13)
        return false;
    if(len == 13)
    {
        if(!isbn.startsWith("978"))
            return false;
    }
    QRegExp exp(QString("^[0-9]+$"));
    if(isbn.contains(exp))
        return false;
    return true;
}
